import os
import xbmc
import xbmcgui
import xmlrpclib
import thread
import time
import tempfile
import datetime
import sys
import string
import pickle
import datetime
import re

from os.path import join as pjoin
import subprocess as subp

home_dir = os.path.expanduser("~")
conference_dir = os.path.join(home_dir, ".qlive/conference")

# save running message
def log(message) :
	f = conference_dir+"/Log_ConferenceWindow.qlive"
	log = open( f, "a")
	owner = "Xbmc_ConferenceWindow"
	time = str(datetime.datetime.now())
	#log.write("[%s] [%s] %s\n" % (time,owner,message))
	os.system("echo [%s] [%s] %s >> %s" % (time,owner,message, f))
	log.close()

## ConferenceWindow
###############################################
class ConferenceWindow(xbmcgui.Window) :
	BWCK = False
	PGRN = False
	
	# is closed
	CLOSE = False
	
	# default constructor 
	def __init__(self):
		log("init variable")
		self.initVariable()
		log("init component")
		self.initComponent()

	# initailize component
	def initComponent(self):
		#prefer resolution = 1280 x 900 = 1
		self.setCoordinateResolution(1)
		
		self.logoBox = xbmcgui.ControlImage( self.screenW - 300 , 0, 248,103, os.path.join( os.getcwd(), 'qlive-logo2.jpg'))
		
		self.backLogo = xbmcgui.ControlImage(0,0, self.screenW, 103,  os.path.join(os.getcwd(), 'bg_back.png'))
		self.backBox = xbmcgui.ControlImage(0,0, self.screenW, self.screenH,  os.path.join(os.getcwd(), 'The_Tree_of_life_1280.jpg'))
		self.bgContact = xbmcgui.ControlImage( 0 , 0, 500,500, os.path.join( os.getcwd(), 'bgcontact.jpg'))

		self.addControl(self.backBox)
		self.addControl(self.bgContact)
		
		self.addControl(self.backLogo)
		self.addControl(self.logoBox)
		
		self.backTitle = xbmcgui.ControlImage(100,165,1000,30, os.path.join(os.getcwd(),'bc-bg-corners.gif'))
		self.addControl(self.backTitle)
		
		self.roomLabel = xbmcgui.ControlLabel(120,170,200,100,"Room", textColor="0xFF000000")
		self.addControl(self.roomLabel)
		self.attendantLabel = xbmcgui.ControlLabel(800,170,200,100,"Attendant", textColor="0xFF000000")
		self.addControl(self.attendantLabel)
		self.startLabel = xbmcgui.ControlLabel(970,170,200,100,"Start - End", textColor="0xFF000000")
		self.addControl(self.startLabel)

		self.roomList = xbmcgui.ControlList(100,200,1000,400,imageWidth=50, imageHeight=50,
			textColor='0xFF000000'	, font='Thai_RSS', buttonFocusTexture =  os.path.join( os.getcwd(), 'bc-bg-corners.gif'))
		
		self.addControl(self.roomList)
		
		self.updateConferenceWindow()
		
		# date label
		date = time.ctime(time.time())
		self.dateLabel = xbmcgui.ControlLabel(100,650, 500,200, str(date), textColor="0xFF000000");
		self.addControl(self.dateLabel)
		
		thread.start_new_thread(self.updateTimeLabel, (1,))
		log("update time label ")
		
		self.setFocus(self.roomList)

		log("set fucus")
		
	# update time label (bottom of the screen)
	def updateTimeLabel(self, delay) :
		while not ConferenceWindow.CLOSE :
			date = time.ctime(time.time())
			self.dateLabel.setLabel(str(date))
			time.sleep(delay)

	# on action event handler
	def onAction(self, action) :
		if action == 10 :
			ConferenceWindow.CLOSE = True
			time.sleep(2)
			log("close window")
			self.close()

	def updateConferenceWindow(self):
		index = 0
		for data in self.data :
		
			room = str(data["ROOM"])
			password = data["PASSWORD"]
			valence = data["VALENCE"]
			attendant = data["ATTENDANT"]
			url = data["URL"]
			description = data["DESCRIPTION"]
			start=data["START"]
			end = data["END"]
			appid = data["APP_ID"]
		
			if not password :
				password = ''
			else :
				npassword = []
				for p in password :
					passwd = string.join(p)
					npassword.append(passwd)
					password = npassword	
			print "Password ", password

			startText = str(start)
			endText = str(end)
			startText = startText[-8:-3]
			endText = endText[-8:-3]	

			sec= {}
			sec['appid'] = appid
			sec['password'] = password
			sec['url'] = url
			self.secret[room  + str(index)] = sec 
			
			label1 = str(room) + "  %s %s" % (description, "")
			label2 = '%d/%d               %s  - %s' % (attendant, valence, startText, endText)

			image1 = os.path.join(os.getcwd(),'conlogo.png');

			listItem = xbmcgui.ListItem(label1, label2, image1 , image1)

			self.roomList.addItem(listItem)
			index +=1			

	##################################################
	##### get server bandwidth #######################
	##################################################
	def getServerBandwidth(self, something):
		# disable bandwidth checker
		if True :
				return "0", "Mbits"

		global conference_dir

		ConferenceWindow.BWCK = True
		
		thread.start_new_thread(self.showProgressDialog,(1,))
	
		#self.settings['server'] = '192.168.1.100'
		if self.settings['domain'] != '' :
			server = self.settings['domain']
		else :
			server = self.settings['server']
				
		print 'server =', server
		log("check server bandwidth >> %s" %(server))
		
		pattern = '\[.+?\]  0.0-10.0 sec  (.+?) MBytes  (.+?) (.+)/sec'
		outFile = conference_dir + "/Iperf_Bandwidth.qlive"
		program = ['iperf','-c', server ,'>', outFile]
		
		#proc = subp.Popen(program, shell = True)
		#proc.wait()
		os.system(" ".join(program))

		lines = open(outFile,'r').readlines()
		match = re.compile(pattern)
		try :
			(tmp,bandwidth, unit) = match.findall(str(lines))[0]
			ConferenceWindow.BWCK = False
			return bandwidth, unit
		except :
			ConferenceWindow.BWCK = False
			return "0", "Mbits"


	def initVariable(self):
		global conference_dir

		self.proxy = xmlrpclib.ServerProxy( "http://localhost:9001", allow_none=True)
		self.data = self.proxy.getConferenceData2()
		self.secret = {}
		self.screenW = 1280
		self.screenH = 900
		
		f = open(conference_dir + "/Setting_Conference.qlive","rb")
		pk = pickle.Unpickler(f)
		self.settings = pk.load()
		f.close()
	
	def openConferenceWindow(self,url, reffile):
		os.system("wmctrl -s 1")

		target = ["firefox", url]
		self.process = subp.Popen(target,shell=True)
		self.process.wait()
		log("start firefox : " + str(target))

		#time.sleep(4)

		wid_comm = subp.Popen("wmctrl -lp | awk '/Firefox/ {print $1}'", stdout=subp.PIPE, shell=True)
		wid_comm.wait()
		wid = wid_comm.stdout.readline().strip()
		
		#os.system("wmctrl -i -r %s -t 1" % (wid))
		#os.system("wmctrl -s 1")
		log("firefox wid = "+ str(wid))
		
	def createReferenceFile(self):
		global conference_dir
		tempdir = conference_dir
		refname = pjoin(tempdir, "Tmp_ProgramIsRunning.qlive")
		reffile = open(refname,"w")
		reffile.close()
		return os.path.abspath(refname)
	
	def showProgressDialog(self, percent):
		# progress dialog
		# show progress dialog
		
		pDialog = xbmcgui.DialogProgress()
		ret = pDialog.create('QLIVE', 'Checking bandwidth ...')
		
		try :
			p = 1 
			while ConferenceWindow.BWCK == True :
				time.sleep(1)
				pDialog.update(p)
				p+=5
			pDialog.close()
		except : pass
		
	def onControl(self, control):
		if control == self.roomList :
			item = self.roomList.getSelectedItem()
			index = self.roomList.getSelectedPosition()

			print "selected index ", index			
			
			roomId = item.getLabel()[0:3] + str(index)
			appid = self.secret[roomId]['appid']
			secPass = self.secret[roomId]['password']
			secUrl = self.secret[roomId]['url']
			
			#kb = xbmc.Keyboard("", "Enter password", True)
			#kb.doModal()
			
			#if( kb.isConfirmed()) :
			if True :
				#enterPass = kb.getText()

				# not check
				#if(enterPass not in secPass):
				if False :
					print "enter %s, real %s" % (enterPass, secPass)
					xbmcgui.Dialog().ok("Authentication failed", "Wrong password, try again")
				else :
					canJoin = self.proxy.updateConference2(appid)
					if(canJoin) :
						reffile = self.createReferenceFile()
						thread.start_new_thread(self.checkState,(appid,))
						
						bw, unit =  self.getServerBandwidth(0)
						bwNumber = int(bw)
						
						# select proper url
						if bwNumber >= 800 :
							secUrl = secUrl + "hight.html"
						elif bwNumber >= 500 :
							secUrl = secUrl + "medium.html"
						elif bwNumber >= 300 :
							secUrl = secUrl + "low.html"
						else :
							secUrl = secUrl = secUrl + "low.html"
						
						print 'bandwidth = ', bw, unit
						
						self.openConferenceWindow(secUrl, reffile )
					else :
						xbmcgui.Dialog().ok("Can not join","Conference room is full");
						
			print secPass,secUrl
			
	def checkState(self,password):
		global conference_dir

		log("check state " + str(password))

		tempdir = tempfile.gettempdir()
		tempdir = conference_dir
		reffile = pjoin(tempdir, "Tmp_ProgramIsRunning.qlive")
		
		selectedItem = self.roomList.getSelectedItem()
		oldText1 = selectedItem.getLabel()
		oldText2 = selectedItem.getLabel2()
		
		selectedItem.setLabel("Processing ...")
		#selectedItem.setLabel2("processing ...")
		
		print reffile
		while os.path.exists(reffile) :
			time.sleep(2)
			self.setFocus(self.roomList)
			
			print "thread run..."
			
		self.proxy.decreaseAttendant2(password)
		selectedItem.setLabel(oldText1)
		selectedItem.setLabel2(oldText2)
		
	def killProcess(self) :
		#self.process.terminate()
		pass
		
if __name__ == "__main__" :
	window = ConferenceWindow()
	window.doModal()
	del window

